#include "GSemaphore.h"
#include "GError.h"

namespace GThread
{
	// Description: Constructor
	// Return:
	// Notes:
	// -----------------------------------------------------
	GSemaphore::GSemaphore()
	{
		Semaphore = NULL;
		MaximumCount = 0;
		Name = "";
	}

	// Description: Destructor
	// Return:
	// Notes: Releases the semaphore handle
	// -----------------------------------------------------
	GSemaphore::~GSemaphore()
	{
		Release();
	}

	// Description: Resurns the actual handle of the semaphore
	// Return:
	// Notes:
	// -----------------------------------------------------
	void* GSemaphore::GetHandle() const
	{
		return Semaphore;
	}

	// Description: Returns the name of the semaphore
	// Return:
	// Notes:
	// -----------------------------------------------------
	const char* GSemaphore::GetName() const
	{
		return Name.c_str( );
	}

	// Description: Resturns the maximum count of semaphore
	// Return:
	// Notes:
	// -----------------------------------------------------
	GUInt32 GSemaphore::GetMaximumCount() const
	{
		return MaximumCount;
	}

	// Description: Checks if semaphore created or not
	// Return:
	// Notes: True if created, false otherwise
	// -----------------------------------------------------
	bool GSemaphore::IsCreated() const
	{
		return Semaphore != NULL;
	}

	// Description: Acquire semaphore and decreases its value by one. Uses GSynchronizer::WaitFor method.
	// Return: Returns GWaitResult based on wait result
	// Notes1: Semaphore must be created
	// Notes2: If semaphore value reaches zero(becomes signaled) thread starts to wait for other threads to free(unsignal) the semaphore.
	// -----------------------------------------------------
	GWaitResult GSemaphore::Acquire(GUInt32 TimeOut)
	{
		GUtil::GError::DebugCheck(!IsCreated(), "Semaphore is not created.");

		return GSynch::WaitFor(this, TimeOut);
	}

}